package day20180128.testReflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Created by 14394 on 2018/1/28.
 */
public class Test {

    public static void main(String[] args) {
        try {
            Class c1 = Class.forName("day20180128.testReflect.Student");
            Object o1= c1.newInstance();
            Class c2 =Student.class;
            Object o2 = c2.newInstance();
            Class c3 = new Student().getClass();
            Object o3 = c3.newInstance();//调用的无参构造进行实例化

            System.out.println(c1+"   "+c2+"   "+ c3);
            System.out.println(o1+"   "+o2+"   "+ o3);

            //获取所有的属性
            Field[] fs = c1.getDeclaredFields();

            //定义可变长的字符串，用来存储属性
            StringBuffer sb = new StringBuffer();

            sb.append(Modifier.toString(c1.getModifiers()) + "  class " + c1.getSimpleName() + "{ \n");

           //获取里面的每一个属性
            for (Field field:fs){
                sb.append("\t");
                sb.append(Modifier.toString(field.getModifiers())+ " ");//获取属性的修饰符
                sb.append(field.getType().getSimpleName()+ " ");//获取属性的类型的名字
                sb.append(field.getName()+ ";\n"); //属性的名字+回车
            }
            sb.append("}");
            System.out.println(sb);

            //获取特定的属性
            Field nameF = c2.getDeclaredField("name");

            //打破封装性
            nameF.setAccessible(true);//使用反射机制可以打破封装性，导致java对象的属性不安全

            nameF.set(o2,"陈开海");
            System.out.println(nameF.get(o2));

            //获取方法相关的内容
            Method[] methods= c3.getDeclaredMethods();
            System.out.println(methods.toString());
            System.out.println(methods[0].getReturnType());
            System.out.println(methods[0].getParameterTypes().toString());
            System.out.println(c3.getDeclaredMethod("getName"));

            //获取与构造方法相关的内容
            System.out.println(c3.getDeclaredConstructors().toString());
            System.out.println(c3.getDeclaredConstructor());

            //获取与继承相关的内容
            System.out.println(c3.getSuperclass());
            System.out.println(c3.getInterfaces().toString());





        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
